#include <Arduino.h>
#include <ArduinoOTA.h>
#include "WiFi.h"
#include "HTTPClient.h"
#include "ArduinoJson.h"
#include "My_SD.h"
#include <SD.h>
#include "Audio_Play.h"
#include <FS.h>
#include "Audio.h"
#include <PubSubClient.h>
#include "Mp3.h"

extern bool play_flag;
extern Audio audio;
WiFiClient client;
PubSubClient mqttClient(client);

const char* mqttServer = "1.14.32.185";
const char* topic0 = "SBOT/TO_RM";
const char* topic1 = "SBOT/TO_DE";


void connectMQTTserver();
void subscribeTopic(String topicString);
void receiveCallback(char* topic, byte* payload, unsigned int length);
void Order_Handle(uint8_t order);

void setup() {
  //启动核心1
  xTaskCreatePinnedToCore(appCpuLoop,      //具体实现的函数
                          "APP_CPU_LOOP",  //任务名称
                          8192,            //堆栈大小
                          NULL,            //输入参数
                          1,               //任务优先级
                          NULL,            //
                          1                //核心  0\1
  );

  Serial.begin(115200);

  //连接wifi
  uint8_t count = 0;
  WiFi.disconnect(true);
  WiFi.begin("HUAWEI", "88888888");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    count++;
    if (count >= 75) {
      Serial.printf("\r\n-- wifi connect fail! --");
      break;
    }
    vTaskDelay(200);
  }
  Serial.printf("\r\n-- wifi connect success! --\r\n");

  SD_init();

  //初始化音频
  Audio_Play_Init();

  //初始化OTA
  ArduinoOTA.setHostname("4GCar_ESP32");
  ArduinoOTA.setPassword("123456");
  ArduinoOTA.begin();

  //初始化mqtt
  mqttClient.setServer(mqttServer, 1883);
  mqttClient.setCallback(receiveCallback);
  connectMQTTserver();
}

uint32_t time1, time2;
void loop() {
  if (mqttClient.connected()) {  // 如果开发板成功连接服务器
    mqttClient.loop();           // 处理信息以及心跳
  } else {                       // 如果开发板未能成功连接服务器
    connectMQTTserver();         // 则尝试连接服务器
  }
}

//核心1
void appCpuLoop(void* pvParameters) {
  while (1) {
    ArduinoOTA.handle();
    if (play_flag == true) {
      while (audio.isRunning()) {
        audio.loop();
      }
    }
  }
  vTaskDelete(NULL);
}

void connectMQTTserver() {
  String clientId = "4GCar_ESP32";

  // 连接MQTT服务器
  if (mqttClient.connect(clientId.c_str())) {
    subscribeTopic("4GCar/ESP32");  // 订阅指定主题
  } else {
    Serial.print("MQTT Server Connect Failed. Client State:");
    Serial.println(mqttClient.state());
  }
}

void subscribeTopic(String topicString) {
  char subTopic[topicString.length() + 1];
  strcpy(subTopic, topicString.c_str());
  // 通过串口监视器输出是否成功订阅主题以及订阅的主题名称
  if (mqttClient.subscribe(subTopic)) {
    Serial.println("Subscrib Topic success!");
  } else {
    Serial.print("Subscribe Fail...");
  }
}

// 收到信息后的回调函数
void receiveCallback(char* topic, byte* payload, unsigned int length) {
  char msg[length];
  StaticJsonDocument<256> msg_json;
  for (uint i = 0; i < length; i++) {
    msg[i] = payload[i];
  }
  msg[length] = '\0';
  deserializeJson(msg_json, msg);

  if ((String)topic == "4GCar/ESP32") {
    Order_Handle(msg_json["0"]);
  } else return;
}

void Order_Handle(uint8_t order) {
  switch (order) {
    case 0:
      playLastAudio();
      break;
    case 1:
      stopAudio();
      break;
    case 2:
      playNextAudio();
      break;
    case 3:
      add_volume();
      break;
    case 4:
      dec_volume();
      break;
    case 5:
      Play_Other_Laba();
      break;
    case 6:
      Play_Other_Niganma();
      break;
    case 7:
      Play_Other_Rangyixia();
      break;
    case 8:
      Play_Other_Goujiao();
      break;
    default: break;
  }
}